<template>
  <j-modal
    width="100%"
    :title="formData.billType === '1'?'收款':'付款'"
    :maskClosable="false"
    :fullscreen.sync="fullscreen"
    :switch-fullscreen="switchFullscreen"
    :destroyOnClose="true"
    :visible.sync="editModalVisible"
    @cancel="handleCancleDbSync"
    :bodyStyle="{paddingTop:'0px'}"
  >
  <template slot="footer">
    <div style="text-align:right;">
      <a-button @click="handleCancleDbSync">关闭</a-button>
      <a-button type="primary" :loading="syncLoading" :disabled="disableSubmit" @click="handleDbSync">确定</a-button>
    </div>
  </template>
  <div class="table-page-search-wrapper warp">
      <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="formData" :rules="rules">
        <a-divider orientation="left">基本信息</a-divider>
        <a-row :gutter="24">
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="账单编号" prop="billCode">
              <a-input disabled v-model="formData.billCode" placeholder="请输入账单编号"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="业主信息" prop="ownerCode">
              <j-popup
                :value="formData.ownerCode"
                :disabled="disableSubmit"
                org-fields="owner_code,owner_name,owner_type,owner_trade,id_card"
                dest-fields="ownerCode,ownerName,ownerType,ownerTrade,idCard"
                field="ownerCode"
                code="v_xy_park_owner"
                :trigger-change="true"
                @callback="popCallbackOwnerCode"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="账单类型" prop="billType">
              <j-dict-select-tag
                disabled
                v-model="formData.billType"
                placeholder="请选择账单类型"
                dict-code="xy_park_bill_type"
              >
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="应收日期" prop="dueDate">
              <a-date-picker class="input-item" :disabled="disableSubmit" v-model="formData.dueDate" placeholder="请选择应收日期"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="合同">
              <j-popup
                v-model="formData.contractCode"
                :disabled="disableSubmit || !formData.ownerCode"
                :param="formData.ownerCode?{owner_code:formData.ownerCode}:{}"
                org-fields="contract_code"
                dest-fields="contractCode"
                field="contractCode"
                code="xy_park_contractinfo"
              />
            </a-form-model-item>
            <!-- :param="{owner_code:formData.ownerCode}" -->
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="收支账户" prop="customerAccount">
              <j-popup
                v-model="formData.customerAccount"
                :disabled="disableSubmit"
                org-fields="park_number"
                dest-fields="customerAccount"
                field="customerAccount"
                code="v_xy_park_account"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="备注">
              <a-textarea :rows="1" :disabled="disableSubmit" v-model="formData.remark" placeholder="备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">费项</a-divider>
        <a-row :gutter="24">
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="费项编码" prop="costType">
              <j-popup
                v-model="formData.costType"
                :disabled="disableSubmit"
                org-fields="cost_type,cost_name,tax_rate"
                dest-fields="costType,costName,taxRate"
                field="costType"
                code="v_xy_park_cost_type"
                :trigger-change="true"
                @callback="popCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="费项">
              <a-input class="input-item" disabled :value="formData.xyParkCostType && formData.xyParkCostType.costName" placeholder="请输入费项"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="税率(%)">
              <a-input-number class="input-item" disabled :value="formData.xyParkCostType && formData.xyParkCostType.taxRate" placeholder="请输入税率"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="账单金额(元)" prop="amount">
              <a-input-number class="input-item" @change="handleEditPrice" :disabled="disableSubmit" v-model="formData.amount" placeholder="请输入账单金额"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="计费周期" prop="startDate">
              <a-range-picker :disabled="disableSubmit" v-model="term" />
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="不含税金额(元)">
              <a-input-number class="input-item" :value="taxAmount.amountExcludingTax" disabled placeholder="请输入不含税金额"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-model-item label="税额(元)">
              <a-input-number class="input-item" :value="taxAmount.taxAmount" disabled placeholder="请输入税额"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <a-form-model-item label="违约金比例(%)" prop="breachFee">
              <a-input class="input-item" addon-after="%/天" :disabled="disableSubmit" v-model.number="formData.breachFee" placeholder="请输入违约金比例"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <a-divider orientation="left">房源</a-divider>
      <ContractHousesItemsTable :dataSource="formData.houses" :hasAdd="!disableSubmit" ref="ContractHousesItemsTable" />
    </div>
  </j-modal>
</template>
<script>
import { putAction, postAction } from '@/api/manage'
import ContractHousesItemsTable from '@/views/park/contract/modules/ContractHousesItemsTable'
import { getSn } from '@/api/api'
export default {
  name: 'BillListModal',
  components: {
    ContractHousesItemsTable
  },
  data() {
    return {
      editModalVisible: false,
      disableSubmit: false,
      syncLoading: false,
      url: {
        add: '/community/bill/add',
        edit: '/community/bill/edit'
      },
      fullscreen: true,
      switchFullscreen: true,
      formData: {},
      rules: {
        billCode: [
          { required: true, message: '请输入账单编号', trigger: 'blur' }
        ],
        ownerCode: [
          { required: true, message: '请选择对方账户', trigger: 'change' }
        ],
        dueDate: [
          { required: true, message: '请选择应收日期', trigger: 'change' }
        ],
        costType: [
          { required: true, message: '请选择费项', trigger: 'change' }
        ],
        amount: [
          { min: 0, type: 'number', message: '必须大于0', trigger: 'change' },
          { required: true, message: '请输入账单金额', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '请选择计费周期', trigger: 'change' }
        ],
        customerAccount: [
          { required: true, message: '请选择收支账户', trigger: 'change' }
        ]
      },
      snCode: {
        '1': 'XYSK-${YYYY}-####',
        '2': 'XYFK-${YYYY}-####'
      },
      title: ''
    }
  },
  computed: {
    term: {
      get: function() { // 获取值
        return [this.formData.startDate, this.formData.endDate]
      },
      set: function(val) { // 赋值
        this.formData.startDate = val[0]
        this.formData.endDate = val[1]
      }
    },
    taxAmount() {
      const taxRate = this.formData.xyParkCostType ? this.formData.xyParkCostType.taxRate : 0
      const amount = this.formData.amount
      let taxAmount, amountExcludingTax
      if (taxRate && amount) {
        taxAmount = (amount * taxRate) / 100
        amountExcludingTax = amount - taxAmount
      } else {
        taxAmount = 0
        amountExcludingTax = 0
      }
      return {
        taxAmount: taxAmount,
        amountExcludingTax: amountExcludingTax
      }
    }
  },
  methods: {
    getCode(value) {
      getSn(this.snCode[value], {}).then(res => {
        if (res.success) {
          this.formData.billCode = res.result
        }
      })
    },
    add(type) {
      this.formData = {
        costName: '',
        taxRate: '',
        billType: type,
        billSource: 1,
        startDate: '',
        endDate: '',
        billCode: '',
        billStatus: '1',
        clearStatus: '1',
        xyParkCostType: {}
      }
      this.getCode(type)
      this.editModalVisible = true
      this.title = type === '1' ? '收款' : '付款'
    },
    edit(data) {
      this.formData = data
      this.editModalVisible = true
      this.title = data.type === '1' ? '收款' : '付款'
    },
    handleCancleDbSync() {
      this.close()
    },
    handleDbSync() {
      this.$refs['ruleForm'].validate(validate => {
        if (validate) {
          const house = this.$refs.ContractHousesItemsTable.getTableData()
          if (!house.fullData.length) {
            return this.$message.warning('请先选择房源')
          }
          this.updateData()
        }
      })
    },
    close() {
      this.$refs.ruleForm.resetFields()
      this.formData = {}
      this.editModalVisible = false
    },
    onSelectChange({ records }) {
      this.selectedRowKeys = []
      records.forEach(item => {
        this.selectedRowKeys.push(item.id)
      })
      this.selectionRows = records
    },
    handleAdd() {
      this.$refs.HomeListModal.show()
    },
    popCallback(row) {
      this.formData.xyParkCostType = row
      this.formData.costType = row.costType
    },
    popCallbackOwnerCode(row) {
      this.$set(this.formData, 'ownerCode', row.ownerCode)
      this.$set(this.formData, 'contractCode', '')
    },
    handleEditPrice(e) {
      this.handleCalc()
    },
    handleCalc() {
      const amount = this.formData.amount
      const taxRate = this.formData.taxRate
      if (amount && taxRate) {
        this.formData.a = (amount * taxRate) / 100
        this.formData.b = amount - this.formData.a
      }
    },
    updateData() {
      this.syncLoading = true
      const house = this.$refs.ContractHousesItemsTable.getTableData()
      this.formData.houses = house.fullData
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then(res => {
          this.actionSuccess(res)
          this.close()
        })
      } else {
        postAction(this.url.add, this.formData).then(res => {
          this.actionSuccess(res)
          this.close()
        })
      }
    },
    actionSuccess(res) {
      this.syncLoading = false
      if (res.success) {
        this.$emit('ok')
        this.editModalVisible = false
      } else {
        this.$message.warning(res.message)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.input-item{
  width:100%;
}
</style>
